<!--
 * @Descripttion: 新增进货订单
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors  : cxguo
 * @LastEditTime : 2019-12-27 09:31:19
 -->
<template>
  <div>
    <affix>
      <div class="clearfix paddingLR20 btn-wrapper">
        <div class="oper-button btn-group fl">
          <el-button class="fl" type="primary" @click="btnSave">选择商品</el-button>
          <el-input
            v-if="isShowQrcode"
            v-model="dataObj.qrCode"
            style="width:200px;"
            class="fl"
            placeholder="请扫描商品编号/条形码"
            size="mini"
          />
          <el-button class="fl" type="default" @click="()=> {isShowQrcode = !isShowQrcode}">条形码</el-button>
        </div>
        <div class="oper-button btn-group fr">
          <el-button type="default" @click="btnJump2List">历史单据</el-button>
          <el-button type="default" :loading="btnLoading.save" @click="btnSave({auditStatus:'1'})">保存并审核</el-button>
          <el-button type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
          <el-button type="default" :loading="btnLoading.save" @click="btnSave({readd:true})">保存并新增(F9)</el-button>
        </div>
      </div>
    </affix>
    <el-main>
      <el-form
        ref="billForm"
        :model="dataObj"
        :rules="ruleValidator"
        label-position="left"
        label-width="80px"
      >
        <el-card shadow="never">
          <div slot="header" class="header clearfix">
            <div class="fl">
              <slot name="headerLeft">
                <el-form-item label="供应商:" class="supplier" prop="supplierId">
                  <el-select
                    v-model="dataObj.supplierId"
                    remote
                    :loading="btnLoading.supplier"
                    :remote-method="getSuppilers"
                    filterable
                    clearable
                    placeholder="按编号,名称,地址搜索..."
                    @focus="onSupplierFocus"
                  >
                    <el-option
                      v-for="item in optionsData.supplier"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </slot>
            </div>
            <div class="fr">
              <slot name="headerRight">
                <el-form-item class="bill-number white-border" label="单据编号: " prop="billNo">
                  <el-input v-model="dataObj.billNo" size="mini" />
                </el-form-item>
              </slot>
            </div>
            <h2 class="text-center">
              <slot name="headerCenter">商品进货订单</slot>
            </h2>
          </div>
          <slot name="goodsTop">
            <div class="clearfix">
              <div class="fl">
                <el-checkbox v-model="dataObj.isPrint" label="保存后打印" border />
              </div>
              <div class="fr">
                <el-form-item label="经手人:" prop="accountId">
                  <el-select
                    v-model="dataObj.accountId"
                    :filter-method="getAccount"
                    filterable
                    placeholder="请选择"
                    @focus="onAccountFocus"
                  >
                    <el-option
                      v-for="item in optionsData.account"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="业务日期:">
                  <el-date-picker v-model="dataObj.bussinessTime" type="datetime" />
                </el-form-item>
              </div>
            </div>
          </slot>
          <goods-select ref="GoodsSelect" />
          <slot name="goodsBottom">
            <table class="form-bottom" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td align="right" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <div class="w200">
                    <el-form-item label="其他费用:" class="white-border">
                      <el-input v-model="dataObj.otherPrice" />
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="结算账户:" prop="accountId" style="width:100%">
                    <el-select
                      v-model="dataObj.accountId"
                      :filter-method="getAccount"
                      filterable
                      placeholder="请选择"
                      @focus="onAccountFocus"
                    >
                      <el-option
                        v-for="item in optionsData.account"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td align="right">
                  <div class="w200">
                    <el-form-item label="应付金额:" prop="amountPayable">
                      {{ dataObj.amountPayable }}
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="实付金额:" prop="amountPaid">
                    <el-input v-model.number="dataObj.amountPaid" />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td style="padding:0;" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <table class="wfull" border="1" cellspacing="0" cellpadding="0">
                    <tr class="lastrow">
                      <td width="100">
                        备 注:
                      </td>
                      <td class="lastCol">
                        <el-input v-model="dataObj.remarks" class="wfull" type="textarea" />
                      </td>
                    </tr>
                  </table>
                </td>
                <td :width="tableFixedWidth" style="padding:0; position: relative; overflow: hidden;">
                  <el-button class="full-button" type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
                </td>
              </tr>
            </table>
          </slot>
        </el-card>
      </el-form>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import GoodsList from '@/views/goods'
import { addData } from '@/api/bill/bill.js'
import { comboList } from '@/api/supplier'
import { options } from '@/api/shop/account.js'
import { amount } from '@/libs/tools.js'
import { add, update, jump2pages } from './mixins'
import GoodsSelect from '@/views/goods-select'
import Affix from '@/components/Affix'
import { BILL_CAT } from '@/views/utils/config.js'

export default {
  name: 'PurchaseDetail',
  components: { GoodsSelect, Affix },
  filters: {
    goodAmount: function(row) {
      return amount(row.price).multiply(row.num).format()
    }
  },
  mixins: [add, update, oftenuse, jump2pages],
  props: {
    billId: {
      type: String,
      default: null
    },
    operation: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      optionsData: { supplier: [], account: [] },
      isShowQrcode: false,
      ruleValidator: {
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ],
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      },
      tableFixedWidth: 300,
      goodsSelectComp: null
    }
  },
  computed: {
    totalMsg: function() {
      const GoodsSelect = this.goodsSelectComp
      if (!GoodsSelect) return {}
      return GoodsSelect.totalMsg
    }
  },
  watch: {
    'totalMsg': {
      handler(data) {
        const price = data.price || '0.00'
        this.$set(this.dataObj, 'amountPayable', price)
        this.$set(this.dataObj, 'amountPaid', price)
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.goodsSelectComp = this.$refs.GoodsSelect
  },
  created() {
    this.initData()
  },
  methods: {
    btnJump2List() {
      this.jump2List()
    },
    btnAddTableData() {
      this.$layer.iframe.addSingle({
        title: '选择商品',
        area: ['1000px', '400px'],
        name: 'iframe-goods',
        content: {
          content: GoodsList,
          props: {
            oper: 'select'
          }
        }
      })
    },
    btnSave({ readd }) {
      this.handleVali().then(_ => {
        const billdetailList = this.$refs.GoodsSelect.getPostData()
        const bill = this.dataObj
        if (billdetailList.length === 0) return this.$message.error('请选择进货商品！')
        bill.billCat = BILL_CAT.purchase1
        billdetailList.forEach(item => {
          const options = item.options || { unit: [], price: [] }
          item.options = JSON.stringify(options)
        })
        const params = { bill, billdetailList }
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          if (!res.data.flag) return
          if (readd) {
            this.resetData()
          } else {
            this.jump2List()
          }
          this.setBtnLoading('save', false)
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // api
    jump2List() {
      this.$router.push({
        name: 'PurchaseOrderList'
      })
    },
    getAccount(keywords) {
      options({ keywords }).then(res => {
        if (res.data.flag) {
          this.$set(this.optionsData, 'account', res.data.data)
        }
      })
    },
    handleVali() {
      const v1 = this.handleValid('billForm')
      const v2 = this.$refs.GoodsSelect.valiData()
      return Promise.all([v1, v2])
    },
    /**
     * 把商品数据转化成票据商品详情的数据
     */
    formatGoodsData2OrderDetail(tableData) {
      tableData.forEach(item => {
        item.goodsId = item.id
        item.price = item.purchasingPrice
      })
      return tableData
    },
    getSuppilers(keywords) {
      this.setBtnLoading('supplier', true)
      comboList({ keywords }).then(res => {
        this.setBtnLoading('supplier', false)
        if (res.data.flag) {
          this.$set(this.optionsData, 'supplier', res.data.data)
        }
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('supplier', false)
      })
    },
    initData() {
      if (this.operation === 'add') this.initSaveData()
      if (this.operation === 'update') this.initUpdateData()
    },
    /**
     * 保存采购订单
     */
    saveData(params) {
      return new Promise((resolve, reject) => {
        addData(params).then(res => {
          resolve(res)
          if (res.data.flag) return this.$notify.success({ title: '保存成功！' })
          this.$notify.error({ title: '保存失败！', message: res.data.message || '' })
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    /**
     * 重置数据
     */
    resetData() {
      this.initSaveData()
    },
    // on
    onTdMouseEnter(e) {
      const target = e.target
      target.className = 'bg-gay'
    },
    onTdMouseLeave(e) {
      const target = e.target
      target.className = ''
    },
    onSelectionChange(selectData) {
      this.setTableSelectionData('goodsSelect', selectData)
    },
    onAccountFocus(e) {
      this.getAccount()
    },
    onSupplierFocus(e) {
      const value = e.target.value
      if (value !== '') return
      this.getSuppilers(null)
    }
  }
}
</script>
<style lang="scss" scoped>
.header{
  position: relative;
  .supplier{
    width:300px; position:absolute; left: 0; top: 0;
  }
  .bill-number{
    width: 260px;
    position:absolute; right: 0; top: 0;
    color: #b4b4b4; font-size: 12px;
    /deep/.el-form-item__label{ width: 80px !important}
  }
}
.full-button{
  position:absolute; left: 0; top: 0;
  width:100%; height: 100%;
  border-radius:0;
}
.white-border{
  /deep/.el-input__inner{ border: #ffffff 1px solid;}
  /deep/.el-input__inner:focus{
    border: #409EFF solid 1px;
  }
}
.btn-wrapper{
  position: relative;
}
a.block{
  color: #409EFF; display: block;
}
a.block:hover{
  color: #409EFF;
  background: #f3f3f3;
}
table{
  border-collapse: collapse;
  border: 0px solid #e8eaec;
}
table td {
  border-top: 0;
  border-right: 1px solid #e8eaec;
  border-bottom: 1px solid #e8eaec;
  border-left: 0;
}
table tr.lastrow td {
  border-bottom: 0;
}
table tr td.lastCol {
  border-right: 0;
}
.form-bottom{
  border:1px solid #e8eaec; border-top: none; border-collapse:collapse;
  width: 100%;
  td{ padding: 10px 10px;}
  /deep/.el-form-item--small.el-form-item{ margin-bottom: 0; }
}
</style>
